import React, {Component} from 'react';
import {observer, inject} from 'mobx-react';
import {withRouter} from 'react-router';
import {Layout, Form, Button, Input, Icon, message} from 'antd';
import './login.less';
import Logo from './logo.png';

@withRouter
@inject('login')
@observer
class Login extends Component {
  constructor(props) {
    super(props);
    // 判断用户有没有登录
    this.props.login.init();
    if(this.props.login.loginState) {
      this.props.history.push('/');
    }
  }

  onKeyDown = (e) => {
    if (e && e.keyCode == 13) {
      this.onSubmit();
    }
  }

  onSubmit = () => {
    this.props.form.validateFields((err, values) => {
      if(err) {
        message.error('请填完列表的必选项!');
        return;
      }
      this.login(values);
    })
  }

  login = async (data) => {
    let result = await this.props.login.login(data);
    switch(result) {
      case 0:
        message.success('登录成功');
        this.props.history.push('/')
        break;
      case 1:
        break;
      case 2:
        message.error('获取用户信息失败，请刷新试试');
        break; 
    }

  };

  render() {
    let {getFieldDecorator} = this.props.form;
    
    return (<Layout className="login">
        <div className="logo">
          <img src={Logo} />
        </div>
        <div className="title">
          <span>释放微服务的无限可能</span>
        </div>
        <div className="login-form">
          <Form>
            <Form.Item>
              {getFieldDecorator('username', {
                rules: [{
                  required: true,
                  message: '用户名不能为空',
                }],
              })(
                <Input
                  onKeyDown={this.onKeyDown}
                  prefix={<Icon type="user" />} placeholder="请输入邮箱或用户名" />
                )}
            </Form.Item>
            <Form.Item className="password">
              {getFieldDecorator('password', {
                rules: [{
                  required: true,
                  message: '密码不能为空',
                }],
              })(
                <Input
                  onKeyDown={this.onKeyDown}
                  prefix={<Icon type="lock" />} type="password" placeholder="请输入密码" />
                )}
            </Form.Item>
            <Form.Item className="login-form-item-button">
              <Button className="login-form-button" onClick={this.onSubmit} loading={this.props.login.loading}>
                登陆
              </Button>
            </Form.Item>
          </Form>
        </div>
    </Layout>)
  }
}

const WrappedLogin = Form.create({})(Login);
export default WrappedLogin;